necessary=c("adehabitat")
#check if library is installed
installed = necessary %in% installed.packages()
#if library is not installed, install it
if (length(necessary[!installed]) >=1) install.packages(necessary[!installed], dep = T)

#load the libraries
for (lib in necessary) library(lib,character.only=T)

library(SDMTools)

work.dir = "H:/Barra Work Directory/current.esoclim/"; setwd(work.dir)

pnts=cbind(x=c(112,116,116,112), y=c(-11,-11,-18.5,-18.5))
cols = colorRampPalette(c('skyblue','slateblue','forestgreen','yellow','red'))(101)
months=c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')

#####ATTEMPT 1######

sum.temp = NULL

png(paste('sum.temp1.png',sep=''), width=28, height=19, units='cm', res=300, pointsize=5, bg='white')
#make 4 columns of 3 rows of images 
par(mfrow=c(3,4),mar=c(0,1,0,1), oma=c(0,3,3,0))

#read in the ascis
for (ii in 1:12) { cat(ii,'\n')
		tasc.max = read.asc.gz(paste("tasmax", sprintf('%02i',ii), ".asc.gz",sep=''))
		tasc.min = read.asc.gz(paste("tasmin", sprintf('%02i',ii), ".asc.gz",sep=''))
	if (length(sum.temp) == 0) { #if there are no values , populate it
          sum.temp = tasc.max + tasc.min
        } else { #if already has values, add the new values to it
          sum.temp = sum.temp + tasc.max + tasc.min
		 }
    sum.temp = sum.temp/2
	zlim=range(sum.temp, na.rm=T)
	image(sum.temp, ann=FALSE,axes=FALSE,col=cols)
	text (130, -40, months[ii], cex=4)
	legend.gradient(pnts,cols=cols, limits=round(zlim), title='Mean Temp.', cex=3)
}		 

dev.off()

###### notes: for some reason fig 1 works but others seem to need to be at least divided by 2

#####ATTEMPT 2########

png(paste('sum.temp2.png',sep=''), width=28, height=19, units='cm', res=300, pointsize=5, bg='white')
#make 4 columns of 3 rows of images 
par(mfrow=c(3,4),mar=c(0,1,0,1), oma=c(0,3,3,0))

sum.temp=NULL
sum.max=NULL
sum.min=NULL
for (ii in 1:12) { cat(ii,'\n')
		tasc.max = read.asc.gz(paste("tasmax", sprintf('%02i',ii), ".asc.gz",sep=''))
		tasc.min = read.asc.gz(paste("tasmin", sprintf('%02i',ii), ".asc.gz",sep=''))
	if (length(sum.max) == 0) { #if there are no values , populate it
          sum.max = tasc.max
        } else { #if already has values, add the new values to it
          sum.max = sum.max + tasc.max
		 }
	if (length(sum.min) == 0) { #if there are no values , populate it
          sum.min = tasc.min
        } else { #if already has values, add the new values to it
          sum.min = sum.min + tasc.min
		 }
    sum.temp = sum.max + sum.min
	sum.temp = sum.temp/2
	zlim=range(sum.temp, na.rm=T)
	image(sum.temp, ann=FALSE,axes=FALSE,col=cols)
	text (130, -40, months[ii], cex=4)
	legend.gradient(pnts,cols=cols, limits=round(zlim), title='Mean Temp.', cex=3)
}		 

dev.off()

####### this version adds the correct value on top of the previous value.

